package com.supercwn.player.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.supercwn.player.R;
import com.supercwn.player.app.manager.activity.AppManagerActivty;
import com.supercwn.player.app.manager.activity.CleanFileManagerActivity2;
import com.supercwn.player.app.manager.bean.StorageBean;
import com.supercwn.player.app.manager.util.CleanFileManager;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FilterWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Random;
import java.util.Scanner;
import java.util.regex.MatchResult;

import static android.os.Environment.getDataDirectory;
import static android.os.Environment.getDownloadCacheDirectory;
import static android.os.Environment.getExternalStorageDirectory;
import static android.os.Environment.getExternalStorageState;
import static android.os.Environment.getRootDirectory;

/**
 * 类描述：首页
 *
 * @author Super南仔
 * @time 2016-9-19
 */
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private String path1 = "http://192.168.3.214:8112/MP4/34a014ca1fa846bbb5d6776919cb47e8/index.mp4?AuthInfo=vdNn0nS2ob5PU%2Fxn88AfmWaMrbljMFru8edlX7Jha4aqP4B%2BQmT2BCbgZQN%2BefNMKEz7vJH38g79%0Ax81XgsPxrfnsw%2FSFGA2i8%2Fp89aICYpPglyyPyokiUWF5%2Bd9ZaUrpHmY%2FGi0KTKitlPD2sqAtOg%3D%3D%0A&version=3";
//    private String path = "http://baobab.wandoujia.com/api/v1/playUrl?vid=2614&editionType=normal";
    private String path = "http://devimages.apple.com.edgekey.net/streaming/examples/bipbop_4x3/gear3/prog_index.m3u8";
    private ImageView tvImageView;
    private EditText getPlayerUrlText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tvImageView = (ImageView) findViewById(R.id.tv_imageView);
        findViewById(R.id.tv_demand_play).setOnClickListener(this);//点播
        findViewById(R.id.tv_live_play).setOnClickListener(this);//直播
        findViewById(R.id.tv_yuan_sheng_video_player).setOnClickListener(this);
        findViewById(R.id.tv_yuan_sheng_surface_view_player).setOnClickListener(this);
        findViewById(R.id.tv_recycleview_player).setOnClickListener(this);
        findViewById(R.id.get_player_url_text_commit).setOnClickListener(this);
        findViewById(R.id.get_app_text_commit).setOnClickListener(this);
        findViewById(R.id.get_app_text_clean).setOnClickListener(this);

        getPlayerUrlText = (EditText) findViewById(R.id.get_player_url_text);
        WindowManager systemService = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        /**进行学习测试**/
//        getFilePath();
//        String extSDCard = getExtSDCard();
//        Log.i("TGH", "extSDCard  :" + extSDCard);
//        getTest();
//        getContinue();
//        getFileUrl();
//        getPriorityQueue();
        getScanner();

    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.tv_demand_play) {//点播
            Intent demandIntent = new Intent(this, SuperVideoDetailsActivity.class);
            demandIntent.putExtra("isLive", false);
            if (!videoPathList.isEmpty()) {
                demandIntent.putExtra("url", videoPathList.get(0));
            } else {
                demandIntent.putExtra("url", path);
            }
            startActivity(demandIntent);

        } else if (view.getId() == R.id.tv_live_play) {//直播
            Intent liveIntent = new Intent(this, SuperVideoDetailsActivity.class);
            liveIntent.putExtra("isLive", true);
            liveIntent.putExtra("url", "rtmp://live.hkstv.hk.lxdns.com/live/hks");
            startActivity(liveIntent);
        } else if (view.getId() == R.id.tv_recycleview_player) {//列表播放
            Intent listViewIntent = new Intent(this, SuperVideoRecycleViewActivity.class);
            startActivity(listViewIntent);
        } else if (view.getId() == R.id.tv_yuan_sheng_video_player) {//原生VideoView
            Intent liveIntent = new Intent(this, YuanShengVideoViewActivity.class);
            if (!videoPathList.isEmpty()) {
                liveIntent.putExtra("url", videoPathList.get(0));
            } else {
                liveIntent.putExtra("url", path);
            }
            startActivity(liveIntent);
        } else if (view.getId() == R.id.tv_yuan_sheng_surface_view_player) {//原生SurfaceView
            Intent liveIntent = new Intent(this, YuanShengSurfaceViewActivity.class);
            if (!videoPathList.isEmpty()) {
                liveIntent.putExtra("url", videoPathList.get(0));
            } else {
                liveIntent.putExtra("url", path);
            }
            startActivity(liveIntent);

        } else if (view.getId() == R.id.get_player_url_text_commit) {//确认
            Editable text = getPlayerUrlText.getText();
            if (!TextUtils.isEmpty(text)) {
                if (text.toString().contains("http")) {
                    videoPathList.add(text.toString());
                } else {
                    Toast.makeText(this, "播放链接没有http字段，且不是网络视频", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(this, "请输入网络的播放链接", Toast.LENGTH_SHORT).show();
            }
        } else if (view.getId() == R.id.get_app_text_commit) {
            Intent liveIntent = new Intent(this, AppManagerActivty.class);
            startActivity(liveIntent);
        } else if (view.getId() == R.id.get_app_text_clean) {
            Intent liveIntent = new Intent(this, CleanFileManagerActivity2.class);
            startActivity(liveIntent);
        }
    }


    private void getFilePath() {
        IntentFilter intentFilter = new IntentFilter(Intent.ACTION_MEDIA_MOUNTED);//插
        //intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);//拔
        intentFilter.addAction(Intent.ACTION_MEDIA_REMOVED);  //完全拔出
        intentFilter.addDataScheme("file");//没有这行监听不起作用
        registerReceiver(receiver, intentFilter);
    }

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.e("TGH", "action === " + intent.getAction());
            if (intent.getAction().equals("android.intent.action.MEDIA_MOUNTED")) {//U盘插入
                String path = intent.getDataString();
                String pathString = path.split("file://")[1];//U盘路径
                Log.i("TGH", "插入U盘 ：" + pathString);
                insertUSB(pathString);
            } else if (intent.getAction().equals("android.intent.action.MEDIA_REMOVED")) {//U盘拔出
                Log.i("TGH", "移除U盘");
            }
        }
    };
    //获取所有图片路径
    private List<String> imgPathList = new ArrayList<>();
    //获取所有视频路径
    private List<String> videoPathList = new ArrayList<>();

    void insertUSB(String pathString) {
        String imagesPath = pathString + "/shData";
        File file = new File(imagesPath);

        //指定存放图片的文件夹不存在的情况
        if (!file.exists()) {
            Toast.makeText(this, "未在U盘中检测到【video】文件夹，请检查后重试！", Toast.LENGTH_LONG).show();
            return;
        }

        File[] files = file.listFiles();
        //空文件夹的情况
        if (files.length == 0) {
            Toast.makeText(this, "检测到【video】文件夹是空的，请检查后重试！", Toast.LENGTH_LONG).show();
            return;
        }

        for (int i = 0; i < files.length; i++) {
            File imageFile = files[i];
            if (checkIsImageFile(imageFile.getPath())) {//检查文件是不是图片
                imgPathList.add(imageFile.getPath());
            }

            if (checkIsVideoFile(imageFile.getPath())) {
                videoPathList.add(imageFile.getPath());
            }
        }

        if (imgPathList.isEmpty()) {
            Toast.makeText(this, "检测到【video】文件夹中没有图片文件，请检查后重试！", Toast.LENGTH_LONG).show();
            return;
        }
        for (int i = 0; i < imgPathList.size(); i++) {
            Log.e("TGH", "图片list： " + imgPathList.get(i));
        }

        if (videoPathList.isEmpty()) {
            Toast.makeText(this, "检测到【video】文件夹中没有视频文件，请检查后重试！", Toast.LENGTH_LONG).show();
            return;
        }

        for (int i = 0; i < videoPathList.size(); i++) {
            Log.e("TGH", "视频List： " + videoPathList.get(i));
        }

        initAdapter(imgPathList);
    }

    private void initAdapter(List<String> imgPathList) {
        String filePath = imgPathList.get(0);//目前就取一个测试
        File fileImage = new File(filePath);
        Bitmap bm = BitmapFactory.decodeFile(filePath,
                getHeapOpts(fileImage));
        tvImageView.setImageBitmap(bm);// 将数组中的第i张图片放到图片视图
        tvImageView.setAdjustViewBounds(true);// 自动缩放为宽高比
    }


    private boolean checkIsImageFile(String fName) {
        boolean isImageFile;
        int i = fName.lastIndexOf(".");
        // 获取扩展名
        String fileEnd = fName.substring(i + 1, fName.length()).toLowerCase();
        if (fileEnd.equals("jpg") || fileEnd.equals("png") || fileEnd.equals("gif")
                || fileEnd.equals("jpeg") || fileEnd.equals("bmp")) {
            isImageFile = true;
        } else {
            isImageFile = false;
        }
        return isImageFile;
    }

    private boolean checkIsVideoFile(String fName) {
        boolean isImageFile;
        int i = fName.lastIndexOf(".");
        // 获取扩展名
        String fileEnd = fName.substring(i + 1, fName.length()).toLowerCase();
        if (fileEnd.equals("mp4") || fileEnd.equals("rmvb") || fileEnd.equals("flv")
                || fileEnd.equals("wmv") || fileEnd.equals("m3u8")) {
            isImageFile = true;
        } else {
            isImageFile = false;
        }
        return isImageFile;
    }


    // 图片加载的类
    public static BitmapFactory.Options getHeapOpts(File file) {
        BitmapFactory.Options opts = new BitmapFactory.Options();
        // 数字越大读出的图片占用的heap必须越小，不然总是溢出
        if (file.length() < 20480) { // 0-20k
            opts.inSampleSize = 1;// 这里意为缩放的大小
        } else if (file.length() < 51200) { // 20-50k
            opts.inSampleSize = 2;
        } else if (file.length() < 307200) { // 50-300k
            opts.inSampleSize = 4;
        } else if (file.length() < 819200) { // 300-800k
            opts.inSampleSize = 6;
        } else if (file.length() < 1048576) { // 800-1024k
            opts.inSampleSize = 8;
        } else {
            opts.inSampleSize = 10;
        }
        return opts;
    }

    public static String getExtSDCard() {
        File[] files = new File("/mnt").listFiles();
        String sdcard = getExternalStorageDirectory().getAbsolutePath();
        Log.i("TGH", "sdcard :" + sdcard);
        String file;
        for (int i = 0; i < files.length; i++) {
            file = files[i].getAbsolutePath();
            Log.i("TGH", "链接路径   file  :" + file);
            if (!file.equalsIgnoreCase(sdcard) && file.contains("sda")) {
                return file;
            }

        }
        return null;
    }

    private String TAG = "TGH";


    static int cnt;
    String name;

    //static区块用于初始化static变量
    static {
        cnt = 1;
        Log.i("TGH", "静态变量  ：" + cnt);
    }

    //非静态变量的初始化区块,支持"匿名内部类"的初始化
    {
        name = "Mike";
        Log.i(TAG, "非静态变量  ：" + name);
    }

    private void getTest() {
        Integer integer = new Integer(42);
        Integer integer1 = new Integer(42);
        Log.i(TAG, integer + "   " + integer1);
        if (integer == integer1) {//比较的是对象
            Log.i(TAG, "两个对象一样");
        } else {
            Log.i(TAG, "两个对象不一样");
        }

        if (integer.equals(integer1)) {//比较的是句柄
            Log.i(TAG, "两个对象一样");
        } else {
            Log.i(TAG, "两个对象不一样");
        }


        // TODO: 2017/11/10  特殊运算符
        int num = 10;
        //左移位运算符 <<
        /*解释 ：
     例如：3 <<2(3为int型)
　　1）把3转换为二进制数字0000 0000 0000 0000 0000 0000 0000 0011，
　　2）把该数字高位(左侧)的两个零移出，其他的数字都朝左平移2位，
　　3）在低位(右侧)的两个空位补零。则得到的最终结果是0000 0000 0000 0000 0000 0000 0000 1100，
　　转换为十进制是12。
　　移动的位数超过了该类型的最大位数，
　　如果移进高阶位（31或63位），那么该值将变为负值。下面的程序说明了这一点：*/
        Log.i(TAG, "左移位运算符   ：" + (num << 1));
        //右移位运算符 >>
        /*解释 ：
    11 >>2(11为int型)
　　1)11的二进制形式为：0000 0000 0000 0000 0000 0000 0000 1011
　　2)把低位的最后两个数字移出，因为该数字是正数，所以在高位补零。
　　3)最终结果是0000 0000 0000 0000 0000 0000 0000 0010。
　　转换为十进制是2。
　　35 >> 2(35为int型)
　　35转换为二进制：0000 0000 0000 0000 0000 0000 0010 0011
　　把低位的最后两个数字移出：0000 0000 0000 0000 0000 0000 0000 1000
　　转换为十进制： 8*/
        Log.i(TAG, "右移位运算符   ：" + (num >> 1));


        // TODO: 2017/11/10  变量的初始化，静态变量初始化比非静态变量早
        Log.i(TAG, "静态变量  ：" + cnt + "   非静态变量  ：" + name);


    }


    interface Atest {
        String name = null;//默认的为static 或者 final

        void fangFa();//不需要方法体，默认为public 或者 friendly
    }

    public void getContinue() {
        for (int i = 0; i < 20; i++) {
            Log.i(TAG, "开始循环 ：" + i);
            if (i == 5) {
                Log.i(TAG, "找到小五了");
                continue;//继续走
            }

        }
    }


    private void getFileUrl() {
        File dataDirectory = getDataDirectory();//获取 Android 数据目录
        Log.i(TAG, "1  存储路径：   " + dataDirectory);
        File downloadCacheDirectory = getDownloadCacheDirectory();//获取 Android 下载/缓存内容目录。
        Log.i(TAG, "2  存储路径：   " + downloadCacheDirectory);
        File externalStorageDirectory = getExternalStorageDirectory();//获取外部存储目录即 SDCard
        Log.i(TAG, "3  存储路径：   " + externalStorageDirectory);
        String externalStorageState = getExternalStorageState();//获取外部存储设备的当前状态
        Log.i(TAG, "4  存储路径：   " + externalStorageState);
        File rootDirectory = getRootDirectory();//获取 Android 的根目录
        Log.i(TAG, "5  存储路径：   " + rootDirectory);

        List<StorageBean> files = CleanFileManager.listLinkedFiles(externalStorageDirectory + "/");
        Log.i(TAG, "6  存储路径：   " + files);
//        List<StorageBean> linkedFiles = CleanFileManager.getLinkedFiles(externalStorageDirectory + "/");
//        Log.i(TAG, "6  存储路径：   " + linkedFiles);


    }

    private void getPriorityQueue() {
        PriorityQueue<Integer> mPriorityQueue = new PriorityQueue<>();
        Random random = new Random(50);
        for (int i = 0; i < 10; i++) {
            mPriorityQueue.offer(random.nextInt(i + 10));
        }
        Log.i(TAG, "乱的  ：" + mPriorityQueue);
        while (mPriorityQueue.peek() != null) {
            Log.i(TAG, "删除吗  ：" + mPriorityQueue.remove());//移动，相当于重新排序
//            Collections.reverseOrder();
        }

        String aa = "12345672222145777";
        HashSet<Character> characters = new HashSet<>();
        for (char c : aa.toCharArray()) {
            characters.add(c);
        }
        PriorityQueue<Character> characters1 = new PriorityQueue<>(characters);
        Log.i(TAG, "字符串去重  ：" + characters1);


    }

    private String threatData = "58.27.82.161@02/10/2005\n" +
            "204.45.234.40@02/11/2005\n" +
            "58.27.82.161@02/11/2005\n" +
            "[Next long section with differnet data format]";

    private void getScanner() {
        Log.i(TAG, "到底走了没有啊！");
        Scanner scanner = new Scanner(threatData);
        String pattern = "(\\d+[.]\\d+[.]\\d+[.]\\d+)@" +
                "(\\d{2}/\\d{2}/\\d{4})";
        while (scanner.hasNext(pattern)) {
            scanner.next(pattern);
            MatchResult match = scanner.match();
            String ip = match.group(1);
            String date = match.group(2);
            Log.i(TAG, "Threat on %s from %s\n" + date + "   " + ip);
        }
    }

    private <T> void sesst(T t) {
        //无界通配符
        Map<?, ?> m = new HashMap<>();
        return;
    }


//    数组元素比较

//    public static class CompType implements Comparable<CompType>{
//        int shuzu_i;
//        int shuzu_j;
//        private static int shuzu_count = 1;
//
//        public CompType (int n1,int n2){
//            shuzu_i = n1;
//            shuzu_j = n2;
//        }
//
//        public String toString(){
//            String result = "[i="+shuzu_i+" , j = "+shuzu_j+"]";
//            for(shuzu_count++ %3 == 0){
//                result += "\n";
//            }
//            return result;
//        }
//
//        public int compareTo(CompType rv){
//            return (shuzu_i <rv.shuzu_i?-1 : (shuzu_i == rv.shuzu_i ? 0:1));
//        }
//
//        private static Random r = new Random(47);
//        public static Generator<CompType> generator(){
//            return new Generator<CompType>(){
//                public CompType next (){
//                    return new CompType(r.nextInt(100),r.nextInt(100));
//                }
//            };
//        }
//
//    }


    private String read(String filename) throws IOException {
        BufferedReader in = new BufferedReader(new FileReader(filename));
        String s;
        StringBuilder sb = new StringBuilder();
        while ((s = in.readLine()) != null) {
            sb.append(s + "\n");
        }
        return sb.toString();


    }

    static String file = "BasicFileOutput.Out";

    private void BasicFileOutput() throws IOException {
        BufferedReader in = new BufferedReader(new StringReader(read("BasicFileOutput.java")));
        PrintWriter out = new PrintWriter(file);
        int lineCount = 1;
        String s;
        while ((s = in.readLine()) != null) {
            out.println(lineCount++ + ":" + s);
        }
        out.close();
        System.out.println(read(file));

    }

    private void storingAndRecoveringData() throws IOException {
        DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream("Data.txt")));
        out.writeDouble(3.14159);
        out.writeUTF("That was pi");
        out.writeDouble(1.41413);
        out.writeUTF("Square root of 2");
        out.close();
        DataInputStream in = new DataInputStream(new FileInputStream("Data.txt"));
        System.out.println(in.readDouble());
        System.out.println(in.readUTF());
        System.out.println(in.readDouble());
        System.out.println(in.readUTF());
    }

    //读取二进制文件
    private byte[] read2(File bFile) throws IOException {
        BufferedInputStream bf = new BufferedInputStream(new FileInputStream(bFile));
        try {
            byte[] data = new byte[bf.available()];
            bf.read(data);
            return data;
        } finally {
            bf.close();
        }
    }

    private byte[] read2(String bFile) throws IOException {
        return read2(new File(bFile).getAbsoluteFile());
    }

    //标准I/O重定向
    private void redirecting() throws IOException {
        PrintStream console = System.out;
        BufferedInputStream in = new BufferedInputStream(new FileInputStream("Redirecting.java"));
        PrintStream out = new PrintStream(new BufferedOutputStream(new FileOutputStream("test.out")));
        System.setIn(in);
        System.setOut(out);
        System.setErr(out);
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String s;
        while ((s = br.readLine()) != null) {
            System.out.println(s);
        }
        out.close();
        System.setOut(console);


    }
}
